package com.qys.livesMall.file.server.upload.service.impl.oss;

import com.aliyun.oss.model.PutObjectRequest;
import com.qys.livesMall.file.server.upload.service.UploadFileService;
import com.qys.livesMall.file.server.upload.service.impl.local.proper.LocalStorageProperties;
import com.qys.livesMall.file.server.upload.service.impl.oss.proper.OssStorageProperties;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * Created by IntelliJ IDEA.
 * User: dp
 * Date: 2023/05/19
 * Time: 14:16
 * DESCRIPTION: 阿里云oss文件上传
 */
@Component
@Slf4j
public class OssUploadFileServiceImpl extends UploadFileService {


    /**
     * 文件上传
     *
     * @param file     文件流
     * @param filePath 文件路径前缀
     * @param fileName 文件名
     */
    @Override
    @SuppressWarnings("ConstantValue")
    public void uploadFile(MultipartFile file, String filePath, String fileName) {
        String fileNamePath = filePath.substring(1) + fileName;
        log.info("阿里云文件上传路径为: {}", fileNamePath);

        try {
            PutObjectRequest request;

            if (null != file.getBytes()) {
                request = new PutObjectRequest(OssStorageProperties.ossUrl, fileNamePath,
                        new ByteArrayInputStream(file.getBytes()));
            } else if (null != file.getInputStream()) {
                request = new PutObjectRequest(OssStorageProperties.ossUrl, fileNamePath, file.getInputStream());
            } else {
                throw new IllegalArgumentException("upload object is NULL");
            }

            OssStorageProperties.oss.putObject(request);
        } catch (Exception e) {
            log.error("文件上传出错:", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取文件信息
     *
     * @param fileName 文件名
     * @param response
     * @param request
     */
    @Override
    public void getLocalFile(String fileName, HttpServletResponse response, HttpServletRequest request) {

    }

    /**
     * 获取视频第一帧保存为图片信息
     *
     * @param file      文件流
     * @param videoPath 视频地址
     * @param imgPath   图片地址
     * @param type      上传类型
     */
    @Async
    @Override
    public void videoFirstFrames(MultipartFile file, String videoPath, String imgPath, String type) {
        //视频零时保存路径
        String filePath = LocalStorageProperties.localFilePath + videoPath + videoPath.substring(videoPath.lastIndexOf("."));

        try {
            // 将上传的文件保存到临时文件中
            super.uploadFileToLocal(file, filePath);

            //保存第一帧图片信息
            String imageName = super.saveVideoFirstFrames(filePath, imgPath);

            if (null != imageName) {
                //上传图片到oss服务器
                boolean b = uploadFirstFramesImgToOss(imgPath, imageName);

                //更新图片地址到数据库
                if (b) {
                    super.updateImageUrlToVideoStore(videoPath, imgPath + imageName, type);
                }
            }
        } catch (Exception e) {
            log.error("oss视频抽帧出错----->", e);
        } finally {
            //删除零时文件
            //noinspection ResultOfMethodCallIgnored
            new File(filePath).delete();
        }
    }

    /**
     * 上传视频第一帧图片到阿里云服务器
     *
     * @param imgPath   图片路径
     * @param imageName 图片名称
     */
    private boolean uploadFirstFramesImgToOss(String imgPath, String imageName) {
        String filePath = imgPath + imageName;

        //获取本地图片信息
        File localFile = new File(LocalStorageProperties.localFilePath + filePath);

        //上传图片信息
        try {
            //组装请求
            PutObjectRequest request = new PutObjectRequest(OssStorageProperties.ossUrl, filePath.substring(1),
                    new FileInputStream(localFile));
            //上传文件到oss
            OssStorageProperties.oss.putObject(request);
        } catch (FileNotFoundException e) {
            log.error("未获取到本地图片信息:{}", filePath);
            return false;
        }
        //删除缓存文件
        //noinspection ResultOfMethodCallIgnored
        localFile.delete();
        return true;
    }
}
